package com.kla.power.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Wuzh
 * @Description:
 * @Date Created in 22:11 2023-07-02
 * @return
 */
@Slf4j
public class DynamicEasyExcelExportUtils {

    private static final String STATION_SHEET_NAME = "电站信息";
    private static final String INVERTER_SHEET_NAME = "逆变器数据";


    /**
     * 下载文件（自定义头部排列）
     * @param stationHead
     * @param stationContent
     * @param inverterHead
     * @param inverterContent
     * @return
     */
    public static void parseExcel (HttpServletResponse response, String excelTitle, List<List<String>> stationHead, List<List<String>> stationContent, List<List<String>> inverterHead, List<List<String>> inverterContent) throws IOException {
        //将行头部转成easyexcel能识别的部分
        List<List<String>> excelHead = transferHead ( stationHead );
        List<List<String>> inverterHeads = transferHead ( inverterHead );
        writeExcel ( response, excelTitle, excelHead, stationContent, inverterHeads, inverterContent );
    }


    /**
     * 下载Excel
     * @param response
     * @param stationHead
     * @param stationContent
     * @param inverterHead
     * @param inverterContent
     * @throws IOException
     */
    private static void writeExcel (HttpServletResponse response, String excelTitle, List<List<String>> stationHead, List<List<String>> stationContent, List<List<String>> inverterHead, List<List<String>> inverterContent) throws IOException {
        response.setContentType ( "application/vnd.ms-excel" );
        response.setCharacterEncoding ( "UTF-8" );
        String fileName = URLEncoder.encode ( excelTitle, "UTF-8" );
        response.setHeader ( "Content-disposition", "attachment;filename=" + fileName + ".xlsx" );
        response.flushBuffer ();
        int[] mergeColumnIndex = {0, 1, 2, 3, 4};
        int mergeRowIndex = 1;
        ExcelWriter excelWriter = EasyExcel.write ( response.getOutputStream () ).build ();
        //sheet的含义相当于一张工作表
        WriteSheet station = EasyExcel.writerSheet ( 0, STATION_SHEET_NAME ).registerWriteHandler ( ExcelUtil.setExcelBasicStyle () ).registerWriteHandler ( new ExcelMergeUtil ( mergeRowIndex, mergeColumnIndex ) ).head ( stationHead ).build ();
        WriteSheet inverter = EasyExcel.writerSheet ( 1, INVERTER_SHEET_NAME ).registerWriteHandler ( ExcelUtil.setExcelBasicStyle () ).registerWriteHandler ( new ExcelMergeUtil ( mergeRowIndex, mergeColumnIndex ) ).head ( inverterHead ).build ();
        excelWriter.write ( stationContent, station );
        excelWriter.write ( inverterContent, inverter );
        //关闭写入流
        excelWriter.finish ();
    }

    /**
     * 将行头部转成easyexcel能识别的部分
     * @param rowHeads
     * @return
     */
    public static List<List<String>> transferHead (List<List<String>> rowHeads) {
        //将头部列进行反转
        List<List<String>> realHead = new ArrayList<> ();
        if ( CollectionUtils.isNotEmpty ( rowHeads ) ) {
            Map<Integer, List<String>> cellMap = new LinkedHashMap<> ();
            //遍历行
            for ( List<String> cells : rowHeads ) {
                //遍历列
                for ( int i = 0; i < cells.size (); i++ ) {
                    if ( cellMap.containsKey ( i ) ) {
                        cellMap.get ( i ).add ( cells.get ( i ) );
                    } else {
                        cellMap.put ( i, Lists.newArrayList ( cells.get ( i ) ) );
                    }
                }
            }
            //将列一行一行加入realHead
            cellMap.entrySet ().forEach ( item -> realHead.add ( item.getValue () ) );
        }
        return realHead;
    }



    /**
     * 下载子系统发电历史数据
     * @param response
     * @param excelTitle
     * @param dayTitle
     * @param content
     * @return
     */
    public static void parseExcel (HttpServletResponse response, String excelTitle, List<List<String>> dayTitle, List<List<String>> content ) throws IOException {
        //将行头部转成easyexcel能识别的部分
        List<List<String>> excelHead = transferHead ( dayTitle );
        writeExcel ( response, excelTitle, excelHead, content );
    }

    /**
     * 下载Excel
     * @param response
     * @param stationHead
     * @param stationContent
     * @throws IOException
     */
    private static void writeExcel (HttpServletResponse response, String excelTitle, List<List<String>> stationHead, List<List<String>> stationContent ) throws IOException {
        response.setContentType ( "application/vnd.ms-excel" );
        response.setCharacterEncoding ( "UTF-8" );
        String fileName = URLEncoder.encode ( excelTitle, "UTF-8" );
        response.setHeader ( "Content-disposition", "attachment;filename=" + fileName + ".xlsx" );
        response.flushBuffer ();
        int[] mergeColumnIndex = {0, 1, 2, 3, 4};
        int mergeRowIndex = 1;
        ExcelWriter excelWriter = EasyExcel.write ( response.getOutputStream () ).build ();
        //sheet的含义相当于一张工作表
        WriteSheet station = EasyExcel.writerSheet ( 0 ).registerWriteHandler ( ExcelUtil.setExcelBasicStyle () ).registerWriteHandler ( new ExcelMergeUtil ( mergeRowIndex, mergeColumnIndex ) ).head ( stationHead ).build ();
        excelWriter.write ( stationContent, station );
        //关闭写入流
        excelWriter.finish ();
    }

    /**
     * 导出文件测试
     * @param args
     * @throws IOException
     */
    public static void main (String[] args) throws IOException {
        //导出包含数据内容的文件（方式二）
        //头部，第一层
        List<String> head1 = new ArrayList<> ();
        head1.add ( "电站名称" );
        head1.add ( "行政区域" );
        head1.add ( "地址" );
        head1.add ( "方位角" );
        head1.add ( "倾角" );
        head1.add ( "电站类型" );
        head1.add ( "系统类型" );
        head1.add ( "并网日期" );
        head1.add ( "总成本" );
        head1.add ( "建站日期" );
        head1.add ( "管理者" );
        head1.add ( "装机容量" );
        head1.add ( "总发电量" );
        head1.add ( "满发小时" );

        //封装头部
        List<List<String>> allHead = new ArrayList<> ();
        allHead.add ( head1 );

        //封装数据体
        //第一行数据
        List<String> data1 = Lists.newArrayList ( "测试发电站", "安徽省合肥市高新区", "玉兰公馆", "容量100", "满发小时", "10000", "5000", "5000" );
        //第二行数据
        List<String> data2 = Lists.newArrayList ( "测试发电站", "安徽省合肥市高新区", "玉兰公馆", "容量100", "天气", "", "雨天", "雨天" );
        List<List<String>> allData = Lists.newArrayList ( data1, data2 );

        //byte[] stream2 = customerExportExcelFile ( allHead, allData );
        FileOutputStream outputStream2 = new FileOutputStream ( new File ( "D://easyexcel-export-user6.xlsx" ) );
        //outputStream2.write ( stream2 );
        outputStream2.close ();
    }
}
